package com.example.fishdriver.recyclerviewdemo.updatastyle;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;

/**
 * Created by Administrator on 2016/9/19 0019.
 */
public class CustomProgressDrawable extends MaterialProgressDrawable {

    //    旋转因子，调整旋转速度
    private static final int ROTATION_FACTOR = 5 * 360;

    private float rotation;
    private Bitmap mBitmap;
    private Paint mPaint;
    private Animation mAnimation;
    private View mParent;

    public CustomProgressDrawable(Context context, View parent) {
        super(context, parent);
        mParent = parent;
        mPaint = new Paint();
        setupAnimation();
    }

    private void setupAnimation() {
        mAnimation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                setProgressRotation(-interpolatedTime);
            }
        };
        mAnimation.setDuration(1000);
        //无限循环
        mAnimation.setRepeatCount(Animation.INFINITE);
        mAnimation.setRepeatMode(Animation.RESTART);
        //均匀转速
        mAnimation.setInterpolator(new LinearInterpolator());
    }

    public void setmBitmap(Bitmap mBitmap) {
        this.mBitmap = mBitmap;
    }

    @Override
    public void setProgressRotation(float rotation) {
//        super.setProgressRotation(rotation);
        //取负号是为了跟微信保持一致，下拉时逆时针加载时顺时针转，旋转因子是为了调整旋转的速度
        this.rotation = -rotation * ROTATION_FACTOR;
        invalidateSelf();
    }

    @Override
    public void draw(Canvas c) {
//        ObjectAnimator.ofFloat(mParent, "rotation", 0.0F, rotation).setDuration(1000).start();
        Rect bound = getBounds();
        c.rotate(rotation, bound.exactCenterX(), bound.exactCenterY());
        Rect src = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
        c.drawBitmap(mBitmap, src, bound, mPaint);
    }

    /**
     * 放开手后启动的动画开启
     */
    @Override
    public void start() {
//        super.start();
        mParent.startAnimation(mAnimation);
    }




}
